<template>
  <div class="section">
    <div class="section-header">
      <h2>{{ title }}</h2>
      <el-link type="primary" :underline="false" @click="handleMoreClick">{{
        moreText
      }}</el-link>
    </div>

    <!-- 添加加载状态 -->
    <div v-loading="loading" element-loading-text="正在加载推荐歌单...">
      <div class="playlist-grid">
        <div
          v-for="(playlist, index) in playlists"
          :key="index"
          class="playlist-card"
          @click="handlePlaylistClick(playlist)"
        >
          <el-image
            :src="playlist.coverUrl"
            class="playlist-cover"
            fit="cover"
          />
          <div class="playlist-info">
            <h3 class="playlist-title">{{ playlist.playlistName }}</h3>
            <p class="playlist-count">{{ playlist.songCount }}首歌曲</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElNotification } from "element-plus"; // 导入通知组件
import api from "../services/api"; // 导入API模块

export default {
  name: "PlaylistGrid",
  props: {
    title: {
      type: String,
      default: "推荐歌单",
    },
    moreText: {
      type: String,
      default: "更多",
    },
  },
  data() {
    return {
      playlists: [], // 初始化 playlists 数组
      loading: false, // 添加加载状态
      error: null, // 错误状态
    };
  },
  async created() {
    // 组件创建时获取推荐歌单数据
    await this.fetchRecommendedPlaylists();
  },
  methods: {
    async fetchRecommendedPlaylists() {
      this.loading = true;
      try {
        // 调用API获取推荐歌单数据（/playlists/recommended）
        const response = await api.getRecommendedPlaylists();
        console.log("获取推荐歌单成功:", response);

        // 从响应中提取推荐歌单数组，兼容后端返回结构
        const data = response?.data;
        this.playlists =
          (data && (data.recommendations || data.playlists)) || [];
      } catch (error) {
        this.error = error;
        console.error("获取推荐歌单失败:", error);
        // ElNotification({
        //   title: "加载失败",
        //   message: "无法获取推荐歌单，请稍后重试",
        //   type: "error",
        //   duration: 3000,
        // });

        // 回退到默认数据
        this.playlists = this.getFallbackData();
      } finally {
        this.loading = false;
      }
    },

    // 备用数据方案
    getFallbackData() {
      return [
        {
          playlistId: 1,
          playlistName: "默认歌单",
          songCount: 20,
          coverUrl: "https://picsum.photos/200/200?random=99",
        },
        {
          playlistId: 2,
          playlistName: "默认歌单",
          songCount: 20,
          coverUrl: "https://picsum.photos/200/200?random=100",
        },
        {
          playlistId: 3,
          playlistName: "默认歌单",
          songCount: 20,
          coverUrl: "https://picsum.photos/200/200?random=101",
        },
      ];
    },

    handlePlaylistClick(playlist) {
      // 跳转到歌单详情页（PlaylistDetail.vue）
      this.$router.push({
        name: "PlaylistDetail",
        params: { id: playlist.playlistId },
      });
    },

    handleMoreClick() {
      // 跳转到全部歌单页面（PlayList.vue）
      // 兼容路由模式：name、path、以及大小写
      if (this.$router.hasRoute && this.$router.hasRoute("PlayList")) {
        this.$router.push({ name: "PlayList" });
      } else if (this.$router.hasRoute && this.$router.hasRoute("playlist")) {
        this.$router.push({ name: "playlist" });
      } else {
        // 尝试直接跳转到路径
        this.$router.push("/playlist");
      }
    },
  },
};
</script>

<style scoped>
/* 保持原有样式不变 */
.section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  font-size: 24px;
  color: #333;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.section-header h2::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 20px;
  width: 4px;
  background: #6b46c1;
  border-radius: 2px;
}

.playlist-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.playlist-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.playlist-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.playlist-cover {
  width: 100%;
  height: 180px;
  transition: transform 0.3s ease;
}

.playlist-card:hover .playlist-cover {
  transform: scale(1.05);
}

.playlist-info {
  padding: 15px;
}

.playlist-title {
  font-size: 16px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.2s;
}

.playlist-card:hover .playlist-title {
  color: #6b46c1;
}

.playlist-count {
  font-size: 14px;
  color: #888;
}

@media (max-width: 768px) {
  .playlist-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .section-header h2 {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .playlist-grid {
    gap: 15px;
  }

  .playlist-cover {
    height: 150px;
  }
}
</style>
